#include "cppTutorSocketClient.h"
#include "cppTutorSocketException.h"

#include "cppTutorLog.h"
extern CcppTutorLog Log;

#include <iostream>

using namespace std;

ClientSocket :: ClientSocket ( std::string host, int port )
{
    if ( ! Socket::socket() )
    {
        throw SocketException ( "Could not create client socket." );
    }

    if ( ! Socket::connect ( host, port ) )
    {
        throw SocketException ( "Could not bind to port." );
    }
}


const ClientSocket& ClientSocket :: operator << ( const std::string& s ) const
{
  if ( ! Socket::send ( s ) )
    {
      throw SocketException ( "Could not write to socket." );
    }

  return *this;

}

const ClientSocket& ClientSocket :: operator >> ( std::string& s ) const
{
  if ( ! Socket::recv ( s ) )
    {
      throw SocketException ( "Could not read from socket." );
    }

  return *this;
}

//#ifdef SOCKET_UDP

CcppTutorSocketClient :: CcppTutorSocketClient ()
{
    cout << "Creating UDP Client Socket" << endl;
}

CcppTutorSocketClient :: ~CcppTutorSocketClient ()
{
}

void CcppTutorSocketClient :: error(const char *msg)
{
    perror(msg);
    exit(0);
}

int CcppTutorSocketClient :: udp_client(int argc1, char *argv1[])
{
#ifdef WIN32
    // check for windows
#else
    int sock, n;
    unsigned int length;
    struct sockaddr_in server, from;
    struct hostent *hp;
    char buffer[256];
   
    if (argc1 != 3) 
    { 
        printf("Usage: server port\n");
        exit(1);
    }
    sock= socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) 
    {
        error("socket");
    }

    server.sin_family = AF_INET;
    hp = gethostbyname(argv1[1]);
    if (hp==0) 
    {
        error("Unknown host");
    }

    bcopy((char *)hp->h_addr, (char *)&server.sin_addr, hp->h_length);
    server.sin_port = htons(atoi(argv1[2]));
    length=sizeof(struct sockaddr_in);
    printf("Please enter the message: ");
    bzero(buffer,256);
    fgets(buffer,255,stdin);
    n=sendto(sock, buffer, strlen(buffer), 0, (const struct sockaddr *)&server,length);
   
    if (n < 0) 
    {
        error("Sendto");
    }
    n = recvfrom(sock,buffer,256,0,(struct sockaddr *)&from, (socklen_t*)&length);
    if (n < 0) 
    {
        error("recvfrom");
    }
    write(1,"Got an ack: ",12);
    write(1,buffer,n);
    close(sock);
#endif
    return 0;
}

//#endif //SOCKET_UDP
